package blue.datacenter2;

import java.io.IOException;
import java.util.HashMap;

import blue.datacenter2.Message;
import blue.datacenter2.MessageLog;

public class MasterHandler extends Thread implements Handler{
	private ZmqSubscriber sub_;
	private ZmqPublisher log_pub_;
	private HashMap<String,SocketClient> map_;

	public MasterHandler(String port, ZmqPublisher log_pub){
		sub_ = new ZmqSubscriber(port,"");
		log_pub_ = log_pub;
		map_ = new HashMap<String,SocketClient>();
	}

	public void addWriteConn(SocketClient conn){
		String sn = conn.getIP()+":"+conn.getPort();
		map_.put(sn,conn);
	}

	private void pubMsglog(String id, boolean to_machine,Message msg) {
		// Publish Message
		String msg_id = id;
		String msg_send = null;
		String msg_recv = null;
		if (to_machine) {
			msg_send = "TM";
			msg_recv = msg.ip+":"+msg.port;;
		}else {
			msg_send = msg.ip+":"+msg.port;
			msg_recv = "TM";
		}
		String msg_data = msg.data;
		MessageLog log = new MessageLog(msg_id,msg_send,msg_recv,msg_data);
		log_pub_.publish(log.toJSON());
	}
	
	public void run(){
		while(true){
			try {
				// Recv from slave
				String json_str = sub_.recv();
				System.out.println("Recv from slave > "+json_str);
				Message json_obj = new Message(json_str);
				String ip = json_obj.ip;
				String port = json_obj.port;
				String data = json_obj.data;
				// send to machine&logger
				String target_sn = ip+":"+port;
				SocketClient target_conn = map_.get(target_sn);
				if (target_conn!=null) {
					// Write Message & Logger
					System.out.println("Send to Machine > "+data);
					int send_cnt = target_conn.write(data);
					if(send_cnt<=0) {
						if (!target_conn.reconnection()) {
							System.out.println("Machine connection broken.");
							System.exit(-1);
						}
					}
				}else {
					System.out.println("Invalid message from slave > "+json_str);
				}
				pubMsglog("1", true, json_obj);
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

}